#  injector.rb
#
#  This file is part of myvnet.
#
#  Copyright (C) 2008  Filipe David Borba Manana,  fdmanana@gmail.com
#
#  myvnet is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  myvnet is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with myvnet.  If not, see <http://www.gnu.org/licenses/>.
 

require 'rubygems'
require 'libnet4r'
require 'thread'
require 'yaml'
require 'lib/protocols/ethernet'


module Packet
  
  # Injects packets into the network.
  # 
  # Client code invokes the instance method add_packet, which
  # adds a packet to an internal queue that is accessed in a
  # FCFS (First Come First Served) fashion. Worker threads of
  # this class will then retrieve the packets from the queue
  # and inject them into the network.
  #
  class Injector
    
    def initialize(interface)
      @iface = interface            
      @packet_queue = []
      @queue_mutex = Mutex.new
      @empty_queue = ConditionVariable.new
      @worker_threads = ThreadGroup.new
      
      # Create worker threads.
      # They fetch packets from the queue and inject them
      # into the network.
      #
      1.upto(3) do |i|
        
        t = Thread.new(i) { |id|
          Thread.current[:id] = id
          
          while true do
            packet = get_packet
            inject_packet(packet)            
          end
        }
        
        @worker_threads.add t
      end
      
    end
    
    
    # === Synopsis
    # 
    #   Packet::Injector#add_packet(packet, daemon_name)
    #   
    # === Args
    # 
    # +packet+::
    #   A layer 2 packet, of the TCP/IP protocol suite, to inject into
    #   the network. At the moment only Ethernet is supported as a
    #   layer 2 protocol. By other words, it must be an instance of
    #   Ethernet::Packet.
    #   
    # +daemon_name+::
    #   Name of the daemon who invoked this method. Used for debugging
    #   and logging.
    # 
    # === Return
    # 
    # No value.
    # 
    # === Description
    # 
    # Adds a packet, built by a daemon, into the outgoing packets queue.
    # The packet will then be injected to the network as soon as possible.
    #
    def add_packet(packet, daemon_name)
      @queue_mutex.synchronize do
        @packet_queue.push packet
        
        if $log[:packet].debug?
          msg = "Packet added to outgoing queue "
          msg << "by daemon `#{daemon_name}':\n"
          msg << (packet.build_upper_layers.to_yaml)
          $log[:packet].debug msg
        end
        
        @empty_queue.signal
      end
    end
    
    
    private
    
    def get_packet
      packet = nil
      
      @queue_mutex.synchronize do
        @empty_queue.wait(@queue_mutex) if @packet_queue.empty?

        packet = @packet_queue.shift
        
        if $log[:packet].debug?
          thread_id = Thread.current[:id]
          msg = "Packet taken from outgoing queue"
          msg << " by thread `#{thread_id}':\n"
          msg << (packet.build_upper_layers.to_yaml)
          $log[:packet].debug msg
        end
      end     
            
      packet      
    end
    
    
    def inject_packet(packet)
      thread_id = Thread.current[:id]
      
      unless packet.instance_of? Ethernet::Packet
        msg = "Thread `#{thread_id}', invalid packet type to inject:"
        msg << " `#{packet.class.name}'"
        $log[:packet].error msg
        return
      end
                  
      begin
        link = Libnet.new(:link, @iface)
        link.write_bytes packet.to_bstream
      rescue Exception => ex
        msg = "Thread `#{thread_id}' could not inject packet: "
        msg << "#{ex.message}"
        $log[:packet].error msg
        return
      end
      
      msg = "Thread `#{thread_id}' injected packet:\n"
      msg << (packet.to_yaml)
      $log[:packet].info msg
    end
    
  end
  
  
end
